#!/usr/bin/perl

use Cwd 'abs_path';

use Getopt::Std;
getopt("i:o:d", \%args); 
my $input_direc = $args{i};
my $output_direc= $args{o};
my $dir_t= $args{d};

#start
#use Getopt::Long;
#&Getopt::Long::GetOptions(
#'config=s'      => \$config
#);
$line = abs_path($0);
chomp $line;
@DR_array = split('/',$line);
pop(@DR_array);
pop(@DR_array);
$dir = join("/",@DR_array);
#require "$dir/bin/CONFIG.pl";
#getDetails($config);
#my $tped= $args{t};
#my $arraytype= $args{a};
#my $tfam = $args{f};
#my $outdir = $args{o};
#my $dirtemp = $args{d};
#my $input_direc = $config{"INPUT_FOLDER"};
#my $output_direc = $config{"OUTPUT_FOLDER"};
#my $dir_t = $config{"TEMP_FOLDER"};
$input_direc =~ s/\/$//g;
$output_direc =~ s/\/$//g;
$dir_t =~ s/\/$//g;
print "INPUT DIREC:$input_direc\tOUTPUT DIREC:$output_direc\tTEMP DIREC:$dir_t\n";
#end

chomp $input_direc;
chomp $output_direc;
chomp $dir_t;
if($input_direc eq "")
{
	die "entered input directory is empty\n";
	
}
if($output_direc eq "")
{
        die "entered output directory is empty\n";

}
if($dir_t eq "")
{
        die "entered working directory is empty\n";

}

@arr_dir = split("",$input_direc);
$arr_d = @arr_dir;
if($arr_dir[$arr_d-1] eq "/")
{
	$arr_dir[$arr_d-1] = "";
}
$input_direc = join('',@arr_dir);

@arr_dir = split("",$output_direc);
$arr_d = @arr_dir;
if($arr_dir[$arr_d-1] eq "/")
{
        $arr_dir[$arr_d-1] = "";
}
$output_direc = join('',@arr_dir);

#@arr_dir = split("",$dir);
#$arr_d = @arr_dir;
#if($arr_dir[$arr_d-1] eq "/")
#{
#        $arr_dir[$arr_d-1] = "";
#}
#$dir = join('',@arr_dir);

#print "entered path : $dir\n";
$round = sprintf("%.0f", rand()*time());
$rounded = $round."_dirfile";
#system("pwd > $rounded");
#open(DRBUFF,$rounded);
#$line = <DRBUFF>;
#system("rm $rounded");
##$line = abs_path($0);
##chomp $line;
##@DR_array = split('/',$line);
##pop(@DR_array);
##pop(@DR_array);
##$dir = join("/",@DR_array);
#print $input_direc."\n";
#die "entered directory is empty\n";
$dir_inputfile = $round."inputfiles";
system("mkdir -p $dir_t");
system("mkdir -p $output_direc");
#qc start
$qcdir = $round."sampleqc";
system("mkdir $dir_t/$qcdir");

#qcend
system("mkdir $dir_t/$dir_inputfile/");
print "cp $input_direc/* $dir_t/$dir_inputfile/\n";
system("cp $input_direc/* $dir_t/$dir_inputfile/");
system("gunzip $dir_t/$dir_inputfile/*.gz");
#die "Done with convertion";
#Listing all the CEL file names in to file filename.txt
$filename_ind = $round."filename.txt";
system("ls $dir_t/$dir_inputfile > $dir_t/$filename_ind");
#open(BUFF,"<$dir/filename.txt");
open BUFF, "< $dir_t/$filename_ind" or die "Can't open $dir_t/$filename_ind : $!";
@output=<BUFF>;
system("rm -rf $dir_t/$filename_ind");



#Converting each binary cel file to ascii format
$ascii_dir = $round."ascii";
for($i=0;$i<@output;$i++)
{
	#print "converting file " . $output[$i] . "\n";
        if($output[$i] =~ m/CEL|cel/)
        {
                chomp($output[$i]);
		my $cmd = "$dir/bin/apt/bin/apt-cel-convert -f text -o $dir_t/$ascii_dir  $dir_t/$dir_inputfile/" . $output[$i];
		#print "$cmd\n";
		system($cmd);
 	}
}
system("rm -rf $dir_t/$ascii_dir/apt-cel-convert.log");
system("rm -rf $dir_t/$dir_inputfile/*");
system("rm -rf $dir_t/$dir_inputfile");
#die "Done with convertion";


#removing the file filename.txt
#system("rm -rf $dir/filename.txt");
#Listing all the CEL file names in to file filename.txt
system("ls $dir_t/$ascii_dir > $dir_t/$filename_ind");
#open(BUFF,"<$dir/filename.txt");
open BUFF, "< $dir_t/$filename_ind" or die "Can't open $dir_t/$filename_ind : $!";
@output=<BUFF>;
system("rm -rf $dir_t/$filename_ind");

$ascii_dir_out =$ascii_dir."out";
system("mkdir $dir_t/$ascii_dir_out");
#Converting each HTHGU cel file to HGU133A cel file
for($i=0;$i<@output;$i++)
{
    print "About to call script for file " . $output[$i];
     #   if($output[$i] =~ m/CEL/)
      #  {
                chomp($output[$i]);
		#print WRBUFF $output[$i]."\n";
                
	$sys = "/usr/bin/perl  $dir/bin/convert3_hs.pl  ".$output[$i]."  $dir"." $dir_t/$ascii_dir";
	print $sys."\n";
	system($sys);
       # }
}
system("rm -rf $dir_t/$ascii_dir/*");
system("rm -rf $dir_t/$ascii_dir");
system("cp $dir_t/$ascii_dir_out/* $dir_t/$qcdir");
system("/usr/local/biotools/r/R-2.12.2/bin/Rscript $dir/bin/rscript_barcode_presentabsent.R $dir_t/$qcdir/ $dir/bin/rlib");
system("perl $dir/bin/perl_barcode.pl  $dir_t/$qcdir/barcode.txt > $dir_t/$qcdir/result_barcode");
system("perl $dir/bin/perl_frma.pl  $dir_t/$qcdir/frma.txt $dir/bin/spike_probesets.txt> $dir_t/$qcdir/result_spikein");
system("perl $dir/bin/perl_presentabsent.pl  $dir_t/$qcdir/present_absent.txt > $dir_t/$qcdir/result_present_absent");
system("mkdir $dir_t/$qcdir_t");
system("/usr/local/biotools/r/R-2.12.2/bin/Rscript $dir/bin/frmascript.R $dir_t/$qcdir $dir/bin/rlib");
system("mv $dir_t/$qcdir/result.txt $dir_t/$qcdir/result_mad");
$sys = "perl $dir/bin/perl_calc_percentile.pl $dir_t/$qcdir/result_barcode $dir_t/$qcdir/result_spikein $dir_t/$qcdir/result_mad $dir_t/$qcdir/result_present_absent $dir/bin/HGU133_sample_QA $dir_t/$qcdir/sample_qc_output";
print $sys."\n";
system($sys);
system("mv $dir_t/$qcdir/sample_qc_output $output_direc/sample.qc");
system("rm -rf $dir_t/$qcdir/*");
system("rm -rf $dir_t/$qcdir");
#print $ascii_dir."\n";
#sample QC start

#sample QC end
#system("/usr/local/biotools/r/R-2.11.0/bin/R CMD INSTALL $dir/bin/newonehgu133plus2geneccdscdf.tar.gz");

#die "Done with convertion";
#removing the file filename.txt
#system("rm -rf $dir/filename.txt");
#Listing all the converted CEL file names in to file filename.txt
#system("ls $dir/samplefiles1 > $dir/filename.txt");
#open(BUFF,"<$dir/filename.txt");
#open BUFF, "< $dir/filename.txt" or die "Can't open $dir/filename.txt : $!";
#@output=<BUFF>;
#FRMA normalization and calculating present calls for each CEL file
#my $dir_r = $dir."/samplefiles_out";
#for($i=0;$i<@output;$i++)
#{
#	if($output[$i] =~ m/CEL/)
#	{
#		chomp($output[$i]);
#		system("cp $dir/samplefiles1/$output[$i] $dir/samplefiles_out/");
		system("source /home/m081429/.bash_profile");
		print $ascii_dir_out."\n";
		system("/usr/local/biotools/r/R-2.11.0/bin/Rscript $dir/bin/script_conv_frma.R $dir_t/$ascii_dir_out  $dir/bin/rlib");

#		system("rm -rf $dir/samplefiles_out/$output[$i]");
#	}
#}
#system("rm -rf $dir/filename.txt");
my $normalize_file;
my $call_file;
my $normalize_file_out;
my $call_file_out;
$normalize_file = $ascii_dir_out.".normalized";
$call_file = $normalize_file.".call";
$normalize_file_out = $normalize_file.".out";
$call_file_out  = $call_file.".out";
my $line;
my %hash;
open BUFF, "< $dir/bin/common_genes_hthguA_hguA_plus2.txt" or die "Can't open $dir/bin/common_genes_hthguA_hguA_plus2.txt : $!";
#$line = <BUFF>;
while($line = <BUFF>)
{
	chomp $line;
	$line =~ s/\n//g;
	$line =~ s/\r//g;
	@ar_gene = split("\t",$line);
	$hash{$ar_gene[1]} = "k";
}

open BUFF, "< $dir_t/$ascii_dir_out/$normalize_file" or die "Can't open $dir_t/$ascii_dir_out/$normalize_file : $!";
#open(WRBUFF,">$dir_t/$ascii_dir_out/$normalize_file_out");
print "$dir_t/$ascii_dir_out/$normalize_file\n";
open BUFF1, "< $dir_t/$ascii_dir_out/$call_file" or die "Can't open $dir_t/$ascii_dir_out/$call_file : $!";
#open(WRBUFF1,">$dir_t/$ascii_dir_out/$call_file_out");
print "$dir_t/$ascii_dir_out/$call_file\n";
$line = <BUFF>;
chomp $line;
$line =~ s/\n//g;
$line =~ s/\r//g;
@cel_names = split("\t",$line);
#shift(@cel_names);
$len_array = @cel_names;
#print WRBUFF $line;
$line = <BUFF1>;
#print  WRBUFF1 "\t".$line;
for($i=0;$i<@cel_names;$i++)
{
	$name_file  = $cel_names[$i]."";
	$WRBUFF = "WRBUFF".$i;
	open($WRBUFF, ">$output_direc/$name_file");
	print "$output_direc/$name_file\n";
	print $WRBUFF "SEGID"."\t"."EXPR_MEAS"."\t"."CONF"."\t"."CALL"."\n";
	
}
while($line = <BUFF>)
{
	$line1 = <BUFF1>;
        chomp $line;
        $line =~ s/\n//g;
        $line =~ s/\r//g;
	 chomp $line1;
	$line1 =~ s/\n//g;
	$line1 =~ s/\r//g;
	@array = split("\t",$line);
	@array1 = split("\t",$line1);
        if($hash{$array[0]} eq "k" && $hash{$array1[0]} eq "k")
	{
		#print WRBUFF $line."\n";
		for($i=0;$i<@cel_names;$i++)
		{	
			$WRBUFF = "WRBUFF".$i;
			$j = $i;
			$k = $j+$len_array;
			if($hash{$array[0]} eq "k")
			{	
				print $WRBUFF $array[0]."\t".$array[$j]."\t".sprintf("%.2f",$array1[$j])."\t";
				if($array1[$j] < 0.06)
				{
					print $WRBUFF "Y"."\n";
				}
				else
				{
					print $WRBUFF "N"."\n";
				}
			}		
		}

	}
	
}
#system("rm -rf $dir_t/$ascii_dir_out/*");
#system("rm -rf $dir_t/$ascii_dir_out");
close(BUFF);
close(BUFF1);
for($i=0;$i<@cel_names;$i++)
{
        $WRBUFF = "WRBUFF".$i;
	close($WRBUFF);
}
system("rm -rf $dir_t/$ascii_dir_out/*");
system("rm -rf $dir_t/$ascii_dir_out");
#sprintf("%.0f", rand()*time())
#while($line = <BUFF1>)
#{
 #       chomp $line;
  #      $line =~ s/\n//g;
   #     $line =~ s/\r//g;
    #    @array = split("\t",$line);
     #   if($hash{$array[0]} eq "k")
     #   {
     #           print WRBUFF1 $line."\n";
     #   }

#}




